<template>
  <div id="Index">
    <header>
      <ul>
        <li>综合排序</li>
        <li>销量优先</li>
        <li @click="paixv()">价格排序</li>
      </ul>
    </header>
    <div v-for="(item,i) in goodsSort" :key="i">
      <van-card
      :price="item.salePrice"
       desc="描述信息"
      :title="item.productName"
      :thumb="'/static/img/'+item.productImage"
    >
      
      <template #footer>
        <van-button size="mini" @click="addCart(i)">+</van-button>
      </template>
    </van-card>
    </div>
    
  </div>
</template>

<script>
export default {
name:"",
data() {
return {
  sort:0,
  goodslist:[]
}
},
computed:{
  
  goodsSort(){
    let data = this.goodslist;
    if(this.sort==0){
      return data
    }

    return data.sort((a,b)=>{
        return this.sort==1? a.salePrice-b.salePrice : b.salePrice-a.salePrice
    })
  }
},
methods:{
  getList(){
    this.$axios({
      url:'/static/data.json'
    }).then(res=>{
      // console.log(res.result.list)
      this.goodslist = res.result.list
      // console.log(this.goodslist)
    })
  },
  paixv(){
    if(this.sort==1 || this.sort==0){
      this.$toast('降序');
      this.sort=2;
      
    }else{
      this.$toast('升序');
      this.sort=1;
    }
    
  },
  addCart(i){

    let arr = this.goodslist[i];
    let id = arr._id;

    let cartlist = this.$store.state.zkList

    let obj = new Object();
    obj.name = arr.productName;
    obj.nums = 1;
    obj.price = arr.salePrice;
    obj.id = arr._id;
    obj.checked = false;
    obj.img = obj.productImage;

    let index = cartlist.findIndex(item=>{
      return item.id == arr._id
    })

    console.log(index)
    console.log(cartlist)
    
    if(index==-1){
      cartlist.push(obj)
      this.$store.commit("zkaddCart",cartlist)
    }else{
      this.goodslist.map(item=>{
        if(item._id == id){
          item.nums++
        }
      })
      this.$store.commit("zkaddCart",cartlist)
    }

    this.$toast('添加购物车成功');
    this.$router.push('/cart')


  }
},
//生命周期 - 创建完成（访问当前this实例）
created() {

},
//生命周期 - 挂载完成（访问DOM元素）
mounted() {
  this.getList()
}
}
</script>
<style scoped lang="scss">
/* @import url(); 引入css类 */
#Index{
  background:rgb(235, 235, 235);
  header{
    margin-bottom: .3rem;
    background:white;
    width: 100;
    ul{
      width:100%;
      display: flex;
      li{
        width: 33%;
        text-align: center;
        height: .8rem;
        line-height: .8rem;
      }

    }
  }
}

</style>